﻿using Avalonia;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Controls.Converters;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Styling;
using AvaloniaMagicCard.Helpers;
using System;

namespace AvaloniaMagicCard.Views;

public partial class MainView : UserControl
{
    public MainView()
    {
        InitializeComponent();
    }
    protected override void OnLoaded(RoutedEventArgs e)
    {
        base.OnLoaded(e);
        RunMagicAnimation();
    }


    private void RunMagicAnimation()
    {
        var gradientBrush = new LinearGradientBrush()
        {
            StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
            EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative)
        };

        var color0 = ColorToHexConverter.ParseHexString("#5ddcff", AlphaComponentPosition.Leading)!.Value;
        var color1 = ColorToHexConverter.ParseHexString("#3c67e3", AlphaComponentPosition.Leading)!.Value;
        var color2 = ColorToHexConverter.ParseHexString("#4e00c2", AlphaComponentPosition.Leading)!.Value;

        var gradientStop0 = new GradientStop(color0, 0);
        var gradientStop1 = new GradientStop(color1, 0.43);
        var gradientStop2 = new GradientStop(color2, 1);

        gradientBrush.GradientStops.AddRange([gradientStop0, gradientStop1, gradientStop2]);

        PART_MainBorder.BorderBrush = gradientBrush;

        var anim = new Animation() { Duration = TimeSpan.FromSeconds(2), IterationCount = IterationCount.Infinite };

        var keyframe0 = new KeyFrame() { Cue = new Cue(0) };
        keyframe0.Setters.Add(new Setter(LinearGradientBrushHelper.RotateAngleProperty, 0d));
        var keyframe1 = new KeyFrame() { Cue = new Cue(1) };
        keyframe1.Setters.Add(new Setter(LinearGradientBrushHelper.RotateAngleProperty, Math.PI * 2));

        anim.Children.Add(keyframe0);
        anim.Children.Add(keyframe1);

        anim.RunAsync(PART_MainBorder);
    }
}
